package com.chinastock.log;

import constant.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author wangzhendong
 */
public class PerfLogInterceptor  implements HandlerInterceptor {
    private Logger logger = LoggerFactory.getLogger(LogName.PERFORMANCE);
    @Override

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute(Constant.START_TIME,System.currentTimeMillis());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // get executed when there is no error handling this request
        long endTime = System.currentTimeMillis();
        request.setAttribute(Constant.END_TIME,endTime);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if (request.getAttribute(Constant.END_TIME) == null){
            request.setAttribute(Constant.END_TIME,System.currentTimeMillis());
        }
        long duration = (long) request.getAttribute(Constant.END_TIME) - (long) request.getAttribute(Constant.START_TIME);
        logger.info("request processing finished in "+duration+" (ms), at "+request.getAttribute(Constant.END_TIME));
    }
}
